<template>
    <div>
        <el-dialog title="图片裁剪" :visible.sync="dialogVisible" destroy-on-close append-to-body @close="closeCropper">
                 <!-- element 上传图片按钮 -->
            <!-- <el-upload class="upload-demo" action="" drag
                :auto-upload="false" :show-file-list="false" :on-change='changeUpload'>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">点击上传</div>
                <div class="el-upload__tip">支持绝大多数图片格式，单张图片最大支持5MB</div>
            </el-upload> -->
            <div class="cropper-content">
                <div class="cropper" style="text-align:center">
                    <vueCropper
                        ref="cropper"
                        :img="option.img"
                        :outputSize="option.size"
                        :outputType="option.outputType"
                        :info="true"
                        :full="option.full"
                        :canMove="option.canMove"
                        :canMoveBox="option.canMoveBox"
                        :original="option.original"
                        :autoCrop="option.autoCrop"
                        :fixed="option.fixed"
                        :fixedNumber="option.fixedNumber"
                        :centerBox="option.centerBox"
                        :infoTrue="option.infoTrue"
                        :fixedBox="option.fixedBox"
                    ></vueCropper>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeCropper">取 消</el-button>
                <el-button type="primary" @click="finish" :loading="loading">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
// import VueCropper from 'vue-cropper'
export default {
    name: "cropper",
    props: ['imgSrc'],
    data() {
        return {
            // 图片裁剪
            dialogVisible: false,
            // 裁剪配置
            option: {
                img: '',                // 裁剪图片的地址
                name: '',               // 裁剪图片的名称
                info: true,             // 裁剪框的大小信息
                outputSize: 0.8,        // 裁剪生成图片的质量
                outputType: 'png',     // 裁剪生成图片的格式
                canScale: false,        // 图片是否允许滚轮缩放
                autoCrop: true,         // 是否默认生成截图框
                // autoCropWidth: 300,  // 默认生成截图框宽度
                // autoCropHeight: 200, // 默认生成截图框高度
                fixedBox: false,        // 固定截图框大小不允许改变
                fixed: false,           // 是否开启截图框宽高固定比例
                fixedNumber: [1, 1],    // 截图框的宽高比例
                full: true,             // 是否输出原图比例的截图
                canMoveBox: true,       // 截图框能否拖动
                original: false,        // 上传图片按照原始比例渲染
                centerBox: true,        // 截图框是否被限制在图片里面
                infoTrue: true          // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
            },
            // 防止重复提交
            loading:false,
            // 裁剪过后的图片
            imgUrl:""

        };
    },
    watch: {
        imgSrc: {
            handler(newData) {
                console.log('44444444444444', newData)
                if (newData) {
                    this.dialogVisible = true;
                    this.option.name = newData.substring(newData.lastIndexOf('/') + 1) // 图片的名称
                    let format = newData.substring(newData.lastIndexOf('.') + 1)
                    this.option.outputType = format == 'jpg' ? 'jpeg' : format // 生成图片的格式
                    if (newData.includes('http://') || newData.includes('https://')) {
                        this.setImageBase64(newData)
                        // this.option.img = newData
                    } else {
                        this.option.img = newData
                    }
                }
            },
            immediate: true
        }
    },
    methods: {
        // 上传按钮   限制图片大小
        changeUpload(file, fileList) {
            const isLt5M = file.size / 1024 / 1024 < 5
            if (!isLt5M) {
                this.$message.error('上传文件大小不能超过 5MB!')
                return false
            }
            this.fileinfo = file
            console.log(file,'---------file')
            // 上传成功后将图片地址赋值给裁剪框显示图片
            // this.option.img = 'http://apigame.metvv.com/public/storage/topic/20240624/49b2636a1dda7a4a1a19c3e2352c5f2b.png'
            //    this.setImageBase64('http://apigame.metvv.com/public/storage/topic/20240624/49b2636a1dda7a4a1a19c3e2352c5f2b.png')
            // this.$nextTick(() => {
            //   this.option.img = file.url
            //   this.dialogVisible = true
            // })
            console.log(this.option.img,'---------futo')
        },
        // 选择图片（加在图片上的事件，点击图片，获取图片的链接地址）
        selectImage(src){
            // 设置图片Base64
            // this.setImageBase64(src, (base64) => {
            //     this.option.img = base64;
            //     this.dialogVisible = true;
            // });
        },
        // 设置图片Base64
        setImageBase64(imgUrl) {
            // 一定要设置为let，不然图片不显示
            let image = new Image()
            // 解决跨域问题
            image.setAttribute('crossOrigin', 'anonymous');
            console.log('forma3',image)
            image.src = `${imgUrl}` // src 加上时间戳
            let that = this
            image.onload = () => {
                 console.log('format444444444444',image)
                let canvas = document.createElement('canvas');
                canvas.width = image.width;
                canvas.height = image.height;
                let context = canvas.getContext('2d');
                context.drawImage(image, 0, 0, image.width, image.height);
                let quality = 0.8;
                // let format = this.option.name.substring(this.option.name.lastIndexOf('.') + 1)
                // console.log('format',format)
                that.option.img = canvas.toDataURL('image/'+that.option.outputType, quality)
            }
        },
            //将base64转换为file
        dataURLtoFile: function(dataurl, filename) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], filename, { type: mime })
        },
        // 确认裁剪
        finish() {
            this.$refs.cropper.getCropData((data) => {
                this.loading = true;
                let formData = new FormData();
                // 以表单的形式将数据传给服务端
                formData.append("imgBase64", data);
                this.$emit('finishCropper', {dataBase64: data, file: this.dataURLtoFile(data, this.option.name)})
                // 此处上传的地址为模拟地址
                // this.$http.post("saveBase64",formData).then((result)=>{
                //     if(result.code == 10000){
                this.loading = false;
                this.dialogVisible = false;
                //         // 获取服务端返回的裁剪图片地址
                //         this.imgUrl = result.url;
                //     }
                // });
            })
        },
        // 关闭裁剪
        closeCropper(){
            this.dialogVisible = false;
            this.$emit('closeCropper')
        }
    }
};

</script>

<style lang="scss" scoped>
// 图片裁剪样式
.cropper-content {
    .cropper {
        width: auto;
        height: 500px;
    }
}
</style>